import type { Drawing, CreateDrawingRequest, DrawingResponse, DrawingsResponse } from '../types/drawing';

// API 基础 URL
const API_BASE_URL = 'https://server.illli.cc/api';

// 获取认证 token
const getAuthToken = (): string | null => {
  return localStorage.getItem('auth_token');
};

// 创建请求头
const createHeaders = (): HeadersInit => {
  const token = getAuthToken();
  const headers: HeadersInit = {
    'Content-Type': 'application/json',
  };
  
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }
  
  return headers;
};

// 处理 API 响应
const handleResponse = async (response: Response) => {
  if (!response.ok) {
    const errorData = await response.json().catch(() => ({ message: 'Network error' }));
    throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
  }
  return response.json();
};

// 将后端返回的 users 字段规范化为前端使用的 user 字段（并兼容 user 为数组的场景）
const normalizeDrawingUser = (drawing: any) => {
  if (!drawing) return drawing;
  if (drawing.users && !drawing.user) {
    drawing.user = Array.isArray(drawing.users) ? drawing.users[0] : drawing.users;
  }
  if (Array.isArray(drawing.user)) {
    drawing.user = drawing.user[0];
  }
  return drawing;
};

const normalizeDrawingsPayload = <T = any>(payload: T): T => {
  const p: any = payload as any;
  if (p && p.data !== undefined) {
    if (Array.isArray(p.data)) {
      p.data = p.data.map((d: any) => normalizeDrawingUser(d));
    } else if (p.data && typeof p.data === 'object') {
      p.data = normalizeDrawingUser(p.data);
    }
  }
  return p as T;
};

// 保存画作
export const saveDrawing = async (drawingData: CreateDrawingRequest, userId?: number): Promise<Drawing> => {
  try {
    // 确保用户已登录
    const token = getAuthToken();
    if (!token) {
      throw new Error('User not authenticated');
    }
    
    console.log('Saving drawing with data:', drawingData);
    
    // 根据Strapi文档，添加publishedAt字段确保记录被发布
    // 明确指定用户ID以确保正确关联（后端字段为 user）
    const dataWithPublish: any = {
      ...drawingData,
      user: userId ?? (drawingData as any).user ?? (drawingData as any).users,
      publishedAt: new Date().toISOString()
    };
    // 移除旧的 users 字段，避免后端报错 Invalid key users
    delete dataWithPublish.users;
    
    const response = await fetch(`${API_BASE_URL}/drawings`, {
      method: 'POST',
      headers: createHeaders(),
      body: JSON.stringify({ data: dataWithPublish }),
    });
    
    const result: DrawingResponse = await handleResponse(response);
    const normalized = normalizeDrawingsPayload(result) as DrawingResponse;
    console.log('Drawing saved successfully:', normalized);
    return normalized.data;
  } catch (error) {
    console.error('Error saving drawing:', error);
    throw error;
  }
};

// 获取用户的所有画作
export const getUserDrawings = async (userId: number, page: number = 1, pageSize: number = 25): Promise<DrawingsResponse> => {
  try {
    // 确保用户已登录
    const token = getAuthToken();
    if (!token) {
      throw new Error('User not authenticated');
    }
    
    const params = new URLSearchParams({
      'pagination[page]': page.toString(),
      'pagination[pageSize]': pageSize.toString(),
      'populate': 'user',
      'sort': 'createdAt:desc',
      'filters[user][id][$eq]': userId.toString(), // 使用后端字段名 user（单数）
    });
    
    const response = await fetch(`${API_BASE_URL}/drawings?${params}`, {
      method: 'GET',
      headers: createHeaders(),
    });
    
    const result = await handleResponse(response);
    return normalizeDrawingsPayload<DrawingsResponse>(result);
  } catch (error) {
    console.error('Error fetching user drawings:', error);
    throw error;
  }
};

// 根据 ID 获取单个画作
export const getDrawingById = async (id: number): Promise<Drawing> => {
  try {
    const response = await fetch(`${API_BASE_URL}/drawings/${id}?populate[user]=*`, {
      method: 'GET',
      headers: createHeaders(),
    });
    
    const result: DrawingResponse = await handleResponse(response);
    const normalized = normalizeDrawingsPayload(result) as DrawingResponse;
    return normalized.data;
  } catch (error) {
    console.error('Error fetching drawing:', error);
    throw error;
  }
};
    
// 更新画作
export const updateDrawing = async (id: number, drawingData: Partial<CreateDrawingRequest>): Promise<Drawing> => {
  try {
    const response = await fetch(`${API_BASE_URL}/drawings/${id}`, {
      method: 'PUT',
      headers: createHeaders(),
      body: JSON.stringify({ data: drawingData }),
    });
    
    const result: DrawingResponse = await handleResponse(response);
    const normalized = normalizeDrawingsPayload(result) as DrawingResponse;
    return normalized.data;
  } catch (error) {
    console.error('Error updating drawing:', error);
    throw error;
  }
};
    
// 设置画作为公开
export const setDrawingPublic = async (id: number, isPublic: boolean): Promise<Drawing> => {
  try {
    console.log('Setting drawing public status:', { id, isPublic });
    const response = await fetch(`${API_BASE_URL}/drawings/${id}`, {
      method: 'PUT',
      headers: createHeaders(),
      body: JSON.stringify({ 
        data: { 
          isPublic: isPublic,
          publishedAt: new Date().toISOString() // 确保记录保持发布状态
        } 
      }),
    });
    
    const result: DrawingResponse = await handleResponse(response);
    const normalized = normalizeDrawingsPayload(result) as DrawingResponse;
    console.log('Public status update result:', normalized);
    return normalized.data;
  } catch (error) {
    console.error('Error setting drawing public status:', error);
    throw error;
  }
};

// 删除画作
export const deleteDrawing = async (id: number): Promise<void> => {
  try {
    const response = await fetch(`${API_BASE_URL}/drawings/${id}`, {
      method: 'DELETE',
      headers: createHeaders(),
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
  } catch (error) {
    console.error('Error deleting drawing:', error);
    throw error;
  }
};

// 获取公开画作
export const getPublicDrawings = async (
  page: number = 1,
  pageSize: number = 10,
  sortBy: string = 'createdAt:desc'
): Promise<DrawingsResponse> => {
  try {
    const params = new URLSearchParams({
      'pagination[page]': page.toString(),
      'pagination[pageSize]': pageSize.toString(),
      'populate': 'user', // 填充 user 以获取作者信息
      'sort': sortBy,
      'filters[isPublic][$eq]': 'true'
    });
    
    console.log('Fetching public drawings with params:', params.toString());
    
    const response = await fetch(`${API_BASE_URL}/drawings?${params}`, {
      method: 'GET',
      headers: createHeaders(),
    });
    
    const result: DrawingsResponse = await handleResponse(response);
    const normalized = normalizeDrawingsPayload(result) as DrawingsResponse;
    console.log('Public drawings API response:', normalized);
    return normalized;
  } catch (error) {
    console.error('Error fetching public drawings:', error);
    throw error;
  }
};

// 搜索画作
export const searchDrawings = async (query: string, page: number = 1, pageSize: number = 25): Promise<DrawingsResponse> => {
  try {
    const params = new URLSearchParams({
      'pagination[page]': page.toString(),
      'pagination[pageSize]': pageSize.toString(),
      'populate': 'user',
      'sort': 'createdAt:desc',
      'filters[$or][0][title][$containsi]': query,
      'filters[$or][1][tags][$containsi]': query,
    });
    
    const response = await fetch(`${API_BASE_URL}/drawings?${params}`, {
      method: 'GET',
      headers: createHeaders(),
    });
    
    const result = await handleResponse(response);
    return normalizeDrawingsPayload<DrawingsResponse>(result);
  } catch (error) {
    console.error('Error searching drawings:', error);
    throw error;
  }
};